package util;

import java.sql.*;
import java.util.Properties;

public class DBUtil {
    public static void main(String[] args) {
        Connection connection = DBUtil.getConnection();
        System.out.println(connection);
    }
    private static final String USER;//用户名
    private static final String PASSWORD;//密码
    private static final String URL;//url
    private static final String DRIVER;//驱动名

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //读取properties类型文件，获取mysql相关信息
            Properties properties = new Properties();
            properties.load(DBUtil.class.getResourceAsStream("/mysql.properties"));//读取相关的属性值
            USER = properties.getProperty("username");
            PASSWORD = properties.getProperty("password");
            URL = properties.getProperty("url");
            DRIVER = properties.getProperty("driverClassName");
        } catch (Exception e) {
            //若配置文件加载失败，则抛出运行时异常
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() {
        try {
            //Class.forName(DRIVER);
            //jdk1.6及其以上,mysql-connector-java-5.1.5.jar版本以上。可以不用显性注册驱动，会自动完成。
            return DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (Exception e) {
            //若数据库连接失败，抛出运行时异常
            throw new RuntimeException(e);
        }
    }

    //当操作完一次数据库后，都要及时的将连接关闭，以防内存泄漏
    public static void close(ResultSet resultSet,Statement statement,Connection connection) {
        try {
            if(resultSet != null){
                resultSet.close();
            }
            if(statement != null){
                statement.close();
            }
            if(connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            //若数据库操作失败，抛出运行时异常
            throw new RuntimeException(e);
        }
    }
}
